#include "ubuntu_mouse.h"

pthread_t UbuntuMouseEventHandler_t;
void *UbuntuMouseEventHandler(void *args);

extern lv_obj_t *canvas;
extern lv_color_t cbuf[LV_HOR_RES_MAX * LV_VER_RES_MAX];
extern lv_obj_t *img_obj;

bool left_button_down = false;
static int flags = 0;
static int16_t last_x = LV_HOR_RES_MAX / 2;
int16_t last_y = LV_VER_RES_MAX / 2;

void ms_init(void) {
    pthread_create(&UbuntuMouseEventHandler_t, NULL, UbuntuMouseEventHandler,
                   (void *)0);
}

bool ms_read(struct _lv_indev_drv_t *indev_drv, lv_indev_data_t *data) {
    /*Store the collected data*/
    data->point.x = last_x;
    data->point.y = last_y;
    data->state = left_button_down ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
    // printf("%lu\n", GET_TICK_COUNT() / 1000);
    return false;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/
void *UbuntuMouseEventHandler(void *args) {
    int fd;
    int ret;
    char event[5] = {0};
    static int num = 0;
    fd = open("/dev/input/mouse0", O_RDONLY);
    if (fd < 0) {
        perror("/dev/input/mouse0");
        return NULL;
    }
    while (1) {
        ret = read(fd, &event, 5);
        if (ret <= 0)
            return;
        last_x = last_x + event[1];
        last_x = last_x > (LV_HOR_RES_MAX - 1) ? (LV_HOR_RES_MAX - 1) : last_x;
        last_x = last_x < 0 ? 0 : last_x;
        last_y = last_y - event[2];
        last_y = last_y > (LV_VER_RES_MAX - 1) ? (LV_VER_RES_MAX - 1) : last_y;
        last_y = last_y < 0 ? 0 : last_y;
        // printf("p6el:x = %d  y = %d\n", event[1], event[2]);
        // lv_obj_move_foreground(img_obj);
        // lv_obj_set_pos(img_obj, last_x, last_y);
        if (!left_button_down && (event[0] & 0x01) == 1) {
            printf("left_button_down\n");
            left_button_down = true;
        } else if (left_button_down && (event[0] & 0x01) == 0) {
            left_button_down = false;
        }
#if MS_TEST
        lv_canvas_set_px(canvas, last_x, last_y, LV_COLOR_RED);
        lv_canvas_set_px(canvas, (last_x + 1) > 479 ? 479 : (last_x + 1),
                         last_y, LV_COLOR_RED);
        lv_canvas_set_px(canvas, last_x,
                         (last_y + 1) > 799 ? 799 : (last_y + 1), LV_COLOR_RED);
        lv_canvas_set_px(canvas, (last_x + 1) > 479 ? 479 : (last_x + 1),
                         (last_y + 1) > 799 ? 799 : (last_y + 1), LV_COLOR_RED);
#endif
    }
    /*关闭设备文件句柄*/
    close(fd);
}
